package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"net/http"
	"time"
	"zg4_month_exam/user/rpc/internal/models"
	"zg4_month_exam/user/rpc/internal/svc"
	"zg4_month_exam/user/rpc/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UploadLogic) Upload(in *user.UploadRequest) (*user.Response, error) {
	// todo: add your logic here and delete this line
	switch in.Choose {
	case 1:
		fmt.Println(111)
		//上传成功随机生成commit id
		Id := int(in.CommitId) + rand.Int() + int(time.Now().Unix())
		fmt.Println(Id)
		//文件上传成功添加数据库
		err := models.Create(models.History{
			Id:         int(in.Id),
			Project_id: int(in.ProjectId),
			User_id:    int(in.UserId),
			Name:       in.Name,
			Path:       in.Path,
			Version:    int(in.Version),
			Ms:         in.Ms, //描述
			CommitId:   Id,
		})
		if err != nil {
			return &user.Response{
				Code: -1,
				Msg:  "失败",
				Data: nil,
			}, nil
		}
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
		}, nil
	case 2:
		//根据commitid和ms搜索
		data, err := models.GetData(int(in.CommitId), in.Ms)
		if err != nil {
			return &user.Response{
				Code: -1,
				Msg:  "失败",
				Data: nil,
			}, nil
		}
		fmt.Println(data)
		d, _ := json.Marshal(data)
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
			Data: d,
		}, nil
	case 3:
		//如果文件存储成功同时把信息添加到历史表和文件表里
		//添加到历史表
		err := models.Create(models.History{
			Id:         int(in.Id),
			Project_id: int(in.ProjectId),
			User_id:    int(in.UserId),
			Name:       in.Name,
			Path:       in.Path,
			Version:    int(in.Version),
			Ms:         in.Ms, //描述
			CommitId:   int(in.CommitId)})
		//添加到文件表
		err = models.CreateFile(models.File{
			Id:         int(in.Id),
			Project_id: int(in.ProjectId),
			User_id:    int(in.UserId),
			Name:       in.Name,
			Path:       in.Path,
			Version:    int(in.Version),
		})
		if err != nil {
			return &user.Response{
				Code: -1,
				Msg:  "失败",
				Data: nil,
			}, nil
		}
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
		}, nil
	case 4:
		//回滚到某次提交状态
		data, err := models.GetPath(int(in.Version))
		if err != nil {
			fmt.Println(err.Error())
		}
		//根据历史data.Path修改当前字段
		err = models.UpdateFile(int(in.Id), data.Path)
		if err != nil {
			fmt.Println(err.Error())
		}
		return &user.Response{
			Code: http.StatusOK,
			Msg:  "成功",
		}, nil
	}
	return nil, nil
}
